//
//  CZStatusListViewModel.swift
//  微博
//
//  Created by 范承志 on 16/6/11.
//  Copyright © 2016年 fanchengzhi. All rights reserved.
//

import UIKit
import SDWebImage

class CZStatusListViewModel: NSObject {
    
    //保存微博数据数组
    var dataArray: [CZStatusViewModel] = [CZStatusViewModel]()
    
    //请求首页数据
    func getHomeData(isPullUp: Bool,finish: @escaping (Bool, String)->()){
        
        // isPullUp  = true 代表是上拉加载更多
        // isPullUp  = false 代表是 下拉刷新
        var sinceId: Int64 = 0
        var maxId: Int64 = 0
        
        //如果是上拉加载更多
        if isPullUp {
            
            maxId = dataArray.last?.statusModel?.id ?? 0
            
            //则返回ID小于或等于max_id的微博，默认为0
            if maxId > 0 {
                
                maxId -= 1
            }
            
            sinceId = 0
            
        } else {
            
            sinceId = dataArray.first?.statusModel?.id ?? 0
            
            maxId = 0
            
        }
        
        let message = "没有加载到最新微博数据"
        CZNetworkTools.sharedTools.HomeLoadData(sinceId: sinceId, maxId: maxId, success: { (response) in
            
            //判断response是否为nil 而且是否转成字典
            guard let resDict = response as? [String: Any] else{
                
                print("可能为nil 可能转不出字典")
                
                finish(false, message)
                
                return
                
            }
            
            //判断resDict["statuses"]是否为nil 而且是否可以转成数组
            guard let resArr = resDict["statuses"] as? [[String: Any]] else {
                
                print("可能为nil 可能转不出字典")
                
                finish(false, message)
                
                return
            }
            
            //yyModel使用直接转出数组
            let statusArray = NSArray.yy_modelArray(with: CZHomeModel.self, json: resArr) as! [CZHomeModel]
            
            //创建一个临时可变的数组
            var tempArray: [CZStatusViewModel] = [CZStatusViewModel]()
            
            //遍历
            for model in statusArray {
                let statusViewModel = CZStatusViewModel()
                
                //给其身上的model赋值
                statusViewModel.statusModel = model
                
                //添加ViewModel到数组中
                tempArray.append(statusViewModel)
            }
            
            //保存数据
            //如果是上拉加载更多
            if isPullUp {
                
                self.dataArray = self.dataArray + tempArray
            } else {
                
                //下拉刷新
                self.dataArray = tempArray + self.dataArray
            }
            
            self.loadSingeImage(array: tempArray, finish: finish)
            
        }) { (error) in
            
            print("请求失败",error)
            
            finish(false, message)
        }
    }
}

extension CZStatusListViewModel{
    
    //单张图片下载
    func loadSingeImage(array: [CZStatusViewModel], finish: @escaping (Bool, String)->()){
        
        //创建调度组
        let group = DispatchGroup()
        
        //遍历数组
        for CZStatusViewModel in array{
            
            //如果是原创微博 && conunt == 1
            if CZStatusViewModel.statusModel?.pic_urls?.count == 1 {
                
                let url = URL(string: CZStatusViewModel.statusModel?.pic_urls?.first?.thumbnail_pic ??  "")!
                
                group.enter()
                
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, error, _, _, _) in
                    
                    group.leave()
                    
                })
            }
            
            //如果是转发微博 && count == 1
            if CZStatusViewModel.statusModel?.retweeted_status?.pic_urls?.count == 1{
                
                let url = URL(string: CZStatusViewModel.statusModel?.retweeted_status?.pic_urls?.first?.thumbnail_pic ?? "")!
                
                group.enter()
                
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, error, _, _, _) in
                    
                    
                    group.leave()
                })
            }
        }
        
        //调度组统一监听单张图片是否全部下载完成
        group.notify(queue: .main) {
            
            var message = "没有加载到最新微博数据"
            
            if array.count > 0 {
                
                message = "加载了\(array.count)条微博数据"
                
            }
            
            //代表成功
            finish(true, message)
        }
    }
}
